package com.luke.xiaotiaowa.config;

import com.luke.xiaotiaowa.DynamicSecurityService;
import com.luke.xiaotiaowa.modules.ums.entity.UmsPermEntity;
import com.luke.xiaotiaowa.modules.ums.service.UmsAdminService;
import com.luke.xiaotiaowa.modules.ums.service.UmsPermService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.core.userdetails.UserDetailsService;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * security相关配置
 *
 * @author xiaotiaowa
 * @create 2023/3/24
 */
@Configuration
public class AdSecurityConfig {

    @Autowired
    private UmsAdminService adminService;
    @Autowired
    private UmsPermService permService;

    @Bean
    public UserDetailsService userDetailsService() {
        //获取登录用户信息
        return username -> adminService.loadUserByUsername(username);
    }

    @Bean
    public DynamicSecurityService dynamicSecurityService() {
        return () -> {
            List<UmsPermEntity> perms = permService.getAll();
            Map<String, ConfigAttribute> map = new ConcurrentHashMap<>(perms.size());
            for (var perm : perms) {
                map.put(perm.getUrl(), new org.springframework.security.access.SecurityConfig(perm.getId() + ":" + perm.getName()));
            }
            return map;
        };
    }
}
